import { Permission } from '/@/models';

export interface PermissionTreeItem extends Permission {
  children?: PermissionTreeItem[];
  isLeaf: boolean;
}

export function toTree(permissions: Permission[]) {
  const ptree: {
    [key: string]: PermissionTreeItem;
  } = {};

  for (let item of permissions) {
    ptree[item.key] = {
      ...item,
      isLeaf: true,
      children: [],
    };
  }

  for (let item of permissions) {
    if (item.parent_key) {
      console.log('item:', item)
      ptree[item.parent_key].children?.push(ptree[item.key]);
      ptree[item.parent_key].isLeaf = false;
    }
  }

  const root: PermissionTreeItem = {
    id: 0,
    name: '所有',
    key: 'ALL',
    action: '',
    subject: '',
    parent_key: null,
    is_route: false,
    is_show: true,
    conditions: '',
    isLeaf: false,
    created_at: new Date(),
    updated_at: new Date(),
    children: Object.values(ptree).filter((item) => item.parent_key === null),
  };

  return [root];
}
